import { useState, useCallback, useRef } from 'react';

// 选中的单元格接口
export interface SelectedCell {
  roomId: string;
  date: string;
  roomIndex: number;
  dateIndex: number;
}

// 拖拽选择状态
interface DragSelection {
  isSelecting: boolean;
  startCell: SelectedCell | null;
  currentCell: SelectedCell | null;
}

export const useMultiSelection = () => {
  // 选中的单元格集合
  const [selectedCells, setSelectedCells] = useState<Set<string>>(new Set());

  // 拖拽选择状态
  const [dragSelection, setDragSelection] = useState<DragSelection>({
    isSelecting: false,
    startCell: null,
    currentCell: null,
  });

  // 用于防止点击事件和拖拽事件冲突
  const mouseDownTimeRef = useRef<number>(0);
  const hasDraggedRef = useRef<boolean>(false);

  // 生成单元格唯一标识
  const getCellKey = useCallback((roomId: string, date: string): string => {
    return `${roomId}-${date}`;
  }, []);

  // 检查单元格是否被选中
  const isCellSelected = useCallback(
    (roomId: string, date: string): boolean => {
      return selectedCells.has(getCellKey(roomId, date));
    },
    [selectedCells, getCellKey]
  );

  // 切换单个单元格的选中状态
  const toggleCellSelection = useCallback(
    (roomId: string, date: string) => {
      const cellKey = getCellKey(roomId, date);
      setSelectedCells(prev => {
        const newSet = new Set(prev);
        if (newSet.has(cellKey)) {
          newSet.delete(cellKey);
        } else {
          newSet.add(cellKey);
        }
        return newSet;
      });
    },
    [getCellKey]
  );

  // 添加单元格到选中集合
  const addCellToSelection = useCallback(
    (roomId: string, date: string) => {
      const cellKey = getCellKey(roomId, date);
      setSelectedCells(prev => new Set([...prev, cellKey]));
    },
    [getCellKey]
  );

  // 从选中集合移除单元格
  const removeCellFromSelection = useCallback(
    (roomId: string, date: string) => {
      const cellKey = getCellKey(roomId, date);
      setSelectedCells(prev => {
        const newSet = new Set(prev);
        newSet.delete(cellKey);
        return newSet;
      });
    },
    [getCellKey]
  );

  // 清空所有选中
  const clearSelection = useCallback(() => {
    setSelectedCells(new Set());
  }, []);

  // 开始拖拽选择
  const startDragSelection = useCallback((cell: SelectedCell) => {
    mouseDownTimeRef.current = Date.now();
    hasDraggedRef.current = false;

    setDragSelection({
      isSelecting: true,
      startCell: cell,
      currentCell: cell,
    });
  }, []);

  // 更新拖拽选择
  const updateDragSelection = useCallback(
    (cell: SelectedCell) => {
      if (!dragSelection.isSelecting || !dragSelection.startCell) return;

      hasDraggedRef.current = true;
      setDragSelection(prev => ({
        ...prev,
        currentCell: cell,
      }));
    },
    [dragSelection.isSelecting, dragSelection.startCell]
  );

  // 结束拖拽选择
  const endDragSelection = useCallback(
    (rooms: any[], dates: string[]) => {
      if (
        !dragSelection.isSelecting ||
        !dragSelection.startCell ||
        !dragSelection.currentCell
      ) {
        setDragSelection({
          isSelecting: false,
          startCell: null,
          currentCell: null,
        });
        return;
      }

      const { startCell, currentCell } = dragSelection;

      // 计算选择范围
      const startRoomIndex = Math.min(
        startCell.roomIndex,
        currentCell.roomIndex
      );
      const endRoomIndex = Math.max(startCell.roomIndex, currentCell.roomIndex);
      const startDateIndex = Math.min(
        startCell.dateIndex,
        currentCell.dateIndex
      );
      const endDateIndex = Math.max(startCell.dateIndex, currentCell.dateIndex);

      // 检查是否真的拖拽了（避免误操作）
      const isDragAction =
        hasDraggedRef.current || Date.now() - mouseDownTimeRef.current > 200;

      if (isDragAction) {
        // 批量选择范围内的单元格
        const newSelections = new Set(selectedCells);

        for (
          let roomIndex = startRoomIndex;
          roomIndex <= endRoomIndex;
          roomIndex++
        ) {
          for (
            let dateIndex = startDateIndex;
            dateIndex <= endDateIndex;
            dateIndex++
          ) {
            const room = rooms[roomIndex];
            const date = dates[dateIndex];
            if (room && date) {
              const cellKey = getCellKey(room.id, date);
              newSelections.add(cellKey);
            }
          }
        }

        setSelectedCells(newSelections);
      } else {
        // 短时间点击，切换单个单元格
        toggleCellSelection(startCell.roomId, startCell.date);
      }

      setDragSelection({
        isSelecting: false,
        startCell: null,
        currentCell: null,
      });
    },
    [dragSelection, selectedCells, getCellKey, toggleCellSelection]
  );

  // 获取拖拽选择的范围（用于预览）
  const getDragSelectionRange = useCallback(() => {
    if (
      !dragSelection.isSelecting ||
      !dragSelection.startCell ||
      !dragSelection.currentCell
    ) {
      return null;
    }

    const { startCell, currentCell } = dragSelection;

    return {
      startRoomIndex: Math.min(startCell.roomIndex, currentCell.roomIndex),
      endRoomIndex: Math.max(startCell.roomIndex, currentCell.roomIndex),
      startDateIndex: Math.min(startCell.dateIndex, currentCell.dateIndex),
      endDateIndex: Math.max(startCell.dateIndex, currentCell.dateIndex),
    };
  }, [dragSelection]);

  // 获取选中的单元格数量
  const getSelectedCount = useCallback(() => {
    return selectedCells.size;
  }, [selectedCells]);

  // 获取选中的单元格列表
  const getSelectedCells = useCallback(() => {
    return Array.from(selectedCells);
  }, [selectedCells]);

  return {
    // 状态
    selectedCells,
    dragSelection,

    // 查询函数
    isCellSelected,
    getSelectedCount,
    getSelectedCells,
    getDragSelectionRange,

    // 操作函数
    toggleCellSelection,
    addCellToSelection,
    removeCellFromSelection,
    clearSelection,

    // 拖拽选择函数
    startDragSelection,
    updateDragSelection,
    endDragSelection,
  };
};

export default useMultiSelection;
